﻿using System;
using System.Text;
using System.Xml;

using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;

namespace KubertSoft.MSBuildTasks.Subversion.Svn
{
    /// <summary>
    /// Helps get output items from xml output.
    /// </summary>
    public class XmlDocumentHelper
    {
        /// <summary>
        /// Contains raw text of the xml document.
        /// </summary>
        private readonly StringBuilder _builder = new StringBuilder();

        /// <summary>
        /// The xml document created from original 
        /// </summary>
        private readonly XmlDocument _document = new XmlDocument();

        /// <summary>
        /// The raw text of the xml document.
        /// </summary>
        public string Text { get; private set; }

        /// <summary>
        /// Adds the text line to the document.
        /// </summary>
        /// <param name="line">The line.</param>
        public void AppendLine(string line)
        {
            _builder.AppendLine(line);
        }

        /// <summary>
        /// Builds xml document.
        /// </summary>
        public void Build()
        {
            Text = _builder.ToString();
            _document.LoadXml(Text);
        }

        /// <summary>
        /// Creates task item from XML node.
        /// </summary>
        /// <param name="log">The log.</param>
        /// <param name="key">The key of the task item.</param>
        /// <param name="xpath">The path to the source node.</param>
        /// <returns>Initialized task.</returns>
        protected ITaskItem CreateItemFromXmlNode(TaskLoggingHelper log, string key, string xpath)
        {
            return CreateItemFromXmlNode(log, key, xpath, false);
        }

        /// <summary>
        /// Creates task item from XML node.
        /// </summary>
        /// <param name="log">Logging helper.</param>
        /// <param name="key">The key of the task item.</param>
        /// <param name="xpath">The path to the source node.</param>
        /// <param name="required">The node value is required if set to <c>true</c>.</param>
        /// <returns>Initialized task.</returns>
        protected ITaskItem CreateItemFromXmlNode(TaskLoggingHelper log, string key, string xpath, bool required)
        {
            log.LogMessageFromText(String.Format(Properties.Resources.Svn_SvnClientTaskBase_GettingPropertyFromXml, key, xpath), MessageImportance.Low);
            var node = _document.SelectSingleNode(xpath);
            if (node == null && required)
            {
                throw new ApplicationException(String.Format(Properties.Resources.Svn_SvnClientTaskBase_GettingPropertyFromXmlFailed, key));
            }
            return node == null ? new TaskItem() : new TaskItem(node.InnerText);
        }
    }
}
